<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" clearable :placeholder="'搜索标题'" size="medium"
              @keyup.enter.native="doSearch"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="doSearch" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加样例
            </el-button>
          </span>
        </div>
      </div>

      <!-- Section Table -->
      <vxe-table stripe auto-resize ref="table" :data="dataList" :loading="loading"
        :custom-config="tableCustomConfig" align="center">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
        <vxe-table-column field="title" title="标题" width="200"></vxe-table-column>
        <vxe-table-column field="content" title="内容" show-overflow></vxe-table-column>
        <vxe-table-column field="sortOrder" title="排序" width="100">
          <template v-slot="{ row }">
            <sort-order-editor :value="row.sortOrder" @update="(newValue) => handleSortUpdate(row, newValue)" />
          </template>
        </vxe-table-column>

        <vxe-table-column field="enabled" title="状态" width="100">
          <template v-slot="{ row }">
            <el-switch v-model="row.enabled" @change="(enabled) => handleStatusChange(row, enabled)"
               class="my-2">
              </el-switch>
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150" :visible="false"/>
        <vxe-table-column field="gmtModified" title="修改时间" width="150" />

        <vxe-table-column title="操作" width="100" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"> </el-button>
      </div>

    </el-card>

    <EditDialog ref="editDialog" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import api from '@/common/api';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import {DEFAULT_TABLE_CUSTOM_CONFIG} from "@/common/constants";
import EditDialog from './components/EditDialog.vue';

export default {
  name: 'SampleList',
  components: {
    SortOrderEditor,
    EditDialog
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      // List data
      dataList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10,
      },

    };
  },
  created() {
    this.getDataList();
  },
  methods: {

    // Get section list
    async getDataList() {
      try {
        this.loading = true;
        const params = Object.assign({}, this.query);
        const {data} = await api.admin_getSampleList(params);
        this.dataList = data.data.records;
        this.total = data.data.total;
      } finally {
        this.loading = false;
      }
    },

    // Filter operations
    doSearch() {
      this.query.currentPage = 1;
      this.getDataList();
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getDataList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle CRUD operations
    handleAdd() {
      this.$refs.editDialog.open({});
    },
    handleEdit(row) {
      this.$refs.editDialog.open(row);
    },
    async handleDelete(row) {
      try {
        const confirmResult = await this.$confirm('确认删除该样例?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
        if (confirmResult !== 'confirm') {
          return;
        }
        await api.admin_deleteSample(row.id);
        this.$message.success('删除成功');
        this.getDataList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row, enabled) {
      const data = { id: row.id, enabled };
      try {
        this.loading = true;
        await api.admin_saveSample(data);
        this.$message.success(`更新状态成功：已${enabled ? '启用' : '禁用'}`);
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    async handleSortUpdate(row, newValue) {
      const data = { id: row.id, sortOrder: newValue };
      try {
        this.loading = true;
        await api.admin_saveSample(data);
        this.$message.success('更新排序成功');
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    handleSaveSuccess(data) {
      this.getDataList();
    },

    // Utils
    formatDate(date) {
      return date;
    },
  }
};
</script>

<style scoped>
.filter-row span {
  margin-right: 20px;
}

.filter-row span button {
  margin-top: 5px;
  margin-bottom: 5px;
}

.filter-row span div {
  margin-top: 8px;
}

.panel-options {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .filter-row span {
    margin-right: 5px;
  }

  .filter-row span div {
    width: 80%;
  }
}
</style>
